package com.newcoder.community.quartz;

import com.newcoder.community.entity.DiscussPost;
import com.newcoder.community.service.DiscussPostService;
import com.newcoder.community.service.ElasticSearchService;
import com.newcoder.community.service.LikeService;
import com.newcoder.community.util.CommunityConstant;
import com.newcoder.community.util.CommunityUtil;
import com.newcoder.community.util.RedisKeyUtil;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class PostScoreRefreshJob implements Job , CommunityConstant {
    @Autowired
    private RedisTemplate redisTemplate;
    private static final Logger logger = LoggerFactory.getLogger(PostScoreRefreshJob.class);
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private LikeService likeService;
    @Autowired
    private ElasticSearchService elasticSearchService;
    //牛客纪元
    private static final Date epoch;
    static {
        try {
           epoch = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2014-08-01 00:00:00");
        } catch (ParseException e) {
            throw new RuntimeException("初始化牛客纪元失败！",e);
        }
    }
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
         String key = RedisKeyUtil.getPostScoreKey();
        BoundSetOperations boundSetOperations = redisTemplate.boundSetOps(key);
        if(boundSetOperations.size()==0){
            logger.info("[任务取消] 没有需要刷新的帖子！");
            return;
        }else{
            logger.info("[任务开始] 正在刷新帖子分数："+boundSetOperations.size());
            while(boundSetOperations.size()>0){
                this.refresh((Integer)boundSetOperations.pop());
            }
            logger.info("[任务结束] 帖子分数刷新完毕！");
        }
    }
    public void refresh(int postId){
       DiscussPost post = discussPostService.findDiscussPostById(postId);
        if(post==null){
            logger.error("该帖子不存在：id="+postId);
            return;
        }
        //是否加精
        boolean wonderful = post.getStatus()==1;
        //评论数量
        int commentCount = post.getCommentCount();
        //获取点赞的数量
        long likeCount  = likeService.findEntityLikeCount(ENTITY_TYPE_POST,postId);
        //计算权重
        double w = (wonderful ? 75 : 0)+commentCount*10+likeCount*2;
        //分数=帖子权重+距离的天数
        double score = Math.log10(Math.max(w,1))
                +(post.getCreateTime().getTime()-epoch.getTime())/(1000*60*60*24);
        //更新帖子的分数
        discussPostService.updateScore(postId,score);
        //同步搜索数据
        post.setScore(score);
        elasticSearchService.saveDiscussPost(post);
    }
}
